<template>
  <div>
    <SearchNav />
    <div class="menu_bg">
      <div class="menu">
        <!--Begin 商品分类详情 Begin-->
        <div class="nav">
          <div class="nav_t">全部商品分类</div>
        </div>
        <!--End 商品分类详情 End-->
        <ul class="menu_r">
          <li><router-link :to="{name: 'IndexCenter'}">首页</router-link></li>
          <li><a href="Food.html">美食</a></li>
          <li><a href="Fresh.html">生鲜</a></li>
          <li><a href="HomeDecoration.html">家居</a></li>
          <li><a href="SuitDress.html">女装</a></li>
          <li><a href="MakeUp.html">美妆</a></li>
          <li><a href="Digital.html">数码</a></li>
          <li><a href="GroupBuying.html">团购</a></li>
        </ul>
        <div class="m_ad">中秋送好礼！</div>
      </div>
    </div>

    <div class="l_list">
      <div class="list_t">
        <span class="fl list_or">
          <a href="#" class="now">默认</a>
<!--           <a href="#">
            <span class="fl">销量</span>
            <span class="i_up">销量从低到高显示</span>
            <span class="i_down">销量从高到低显示</span>
          </a> -->
          <a href="#">
            <span class="fl">价格</span>
            <span class="i_up" @click="orderByPriceAsc()">价格从低到高显示</span>
            <span class="i_down" @click="orderByPriceDesc()">价格从高到低显示</span>
          </a>
<!--           <a href="#">新品</a> -->
        </span>
        <span class="fr" v-if="pageInfo != null"
          >共发现{{ pageInfo.totalCount }}件</span
        >
      </div>
      <div class="list_c">
        <ul class="cate_list" v-if="pageInfo != null">
          <div v-if="pageInfo.totalCount == 0">暂无商品</div>
          <template v-if="pageInfo.totalCount &gt; 0">
            <li v-for="product in pageInfo.list" :key="product.id" class="li-product" style="margin:10px 5px">
              <div class="img">
                <a href="javascript:;" @click="getProductDetailById(product.id)"
                  ><img
                    :src="imagesDir + product.fileName"
                    width="210"
                    height="185"
                /></a>
              </div>
              <div class="price">
                <font
                  >￥<span>{{ product.price }}</span></font
                >
              
                <span v-if="product != null && product.stock < 100 && product.stock > 0" style="font-size: 0.8rem; display:inline-block;float: right">仅剩<span style="color: red">{{product.stock}}</span>件</span>
                <span v-if="product != null && product.stock <= 0" style="font-size: 0.8rem; display:inline-block;float: right">已售罄</span>
              </div>
              <div class="name">
                <a
                  href="javascript:;"
                  @click="getProductDetailById(product.id)"
                  v-html="product.name"
                ></a>
              </div>
              <div class="carbg">
                <a href="javascript:;" @click="addToFavorite(product.id)" class="ss">收藏</a>
                <a href="javascript:;" @click='addInCar(product)' class="j_car">加入购物车</a>
              </div>
            </li>
          </template>
        </ul>
      </div>
      
      <div style="width:100%;height:10rem"></div>
      <div v-if="pageInfo != null" style="text-align: right">
        <el-pagination
          background
          layout="prev, pager, next"
          :current-page="pageNum"
          :total="pageInfo.totalCount"
          :page-size="pageInfo.pageSize"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import Vue from "vue";
import { Pagination } from "element-ui";
import SearchNav from "@/components/SearchNav.vue";
Vue.use(Pagination);
export default {
  data() {
    return {
      // searchTxt: sessionStorage.getItem("searchTxt"),
      userId: null,
      pageInfo: {},
      pageNum: 1,
      pageSize: 10,
      roleType: sessionStorage.getItem("type"),
      order: null, //购物车中的订单（isPay状态为-2的订单）
      imagesDir: sessionStorage.getItem("imagesDir"),
    };
  },
  methods: {
    handleCurrentChange(val) {
      this.pageNum = val;
      this.loadListData(this.$props);
    },
    getHighlightProductList(searchTxt) {
      //获取查询高亮商品
      this.$axios({
        url: "/api/product/pageinfo",
        method: "POST",
        data: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          name: searchTxt,
        },
      }).then((rs) => {
        console.log("productList-highlight", rs);
        this.pageInfo = rs.data.pageinfo;
      });
    },
    getProductList() {
      //获取具体某个分类下的所有商品
      this.$axios({
        url: "/api/product/category",
        method: "POST",
        data: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          type: this.type,
          categoryId: this.categoryId,
        },
      }).then((rs) => {
        console.log("productList", rs);
        this.pageInfo = rs.data.pageinfo;
      });
    },
    loadListData(props) {
      console.log("props", props);
      if (props.searchTxt) {
        this.getHighlightProductList(props.searchTxt);
      } else if (props.type) {
        this.getProductList();
      } else {
        this.getHighlightProductList("");
      }
    },
    getProductDetailById(id) {
      this.$router.push({
        name: "GoodsDetail",
        params: {
          id: id,
        },
      });
    },
    addInCar(product) { //将商品加入购物车，每次点击只会 + 1         ----- 用户必须登录才能加入购物车 -----
      if(!this.roleType) {
        this.$message.warning("请先登录！");
        this.$router.push({name: 'Login'});    
        return;
      }
      if(product.stock == 0) {
        this.$message.info("该商品已售罄！");
      }
      //根据product的id实时查询商品的数量，防止多用户下数量不一致
      this.$axios({
        url: '/api/product/detail',
        method: "POST",
        data: {
          id: product.id
        }
      }).then( rs=> {
        console.log("实时查询商品数量", rs.data.product)
        product = rs.data.product;
        if(product.stock >= 1) { //此处为1，是因为每次添加到购物车数量仅为1
          this.subProductStock(product, 1);
          this.addProductNumberInCar(product, 1);
        }
      })
      
    },
    subProductStock(product, number) { //执行商品库存减少操作, 减少的数量为number                       ------ 未写完，此处仅模拟，不涉及es和数据库操作，仅仅对vue中data变量数据的增减 ------
      //先修改页面中展示的数据
      this.pageInfo.list.forEach(i => {
        if(i.id == product.id) {
          i.stock -= number;
        }
      })
      //修改后再修改es中上平的数量
      product.stock -= number;
      this.$axios({
        url: '/api/product/update0',
        method: "POST",
        data: product
      }).then(rs => {
        console.log("修改es单个商品结果", rs.data.msg);
      })
    },
    addProductNumberInCar(product, number) { //执行购物车中商品的增加操作，增加的数量为number
      this.order = this.$store.state.order;
      //先修改页面中的数据及
      let pExist = false; //判断购物车是否有该商品
      if(this.order) {
        if(!this.order.orderDetailList) this.order.orderDetailList = [];
        for(let i = 0; i < this.order.orderDetailList.length; i++) {
          if(this.order.orderDetailList[i].productId == product.id) {
            pExist = true;
            this.order.orderDetailList[i].quantity += number;
            this.order.cost += number * product.price;
            this.order.orderDetailList[i].name = product.name;
            this.order.orderDetailList[i].fileName = product.fileName;
          }
        }
      }
      //购物车中不存在该商品
      if(!pExist) {
        this.order.orderDetailList.push({ 
          productId: product.id,
          quantity: number,
          cost: product.price,
          name: product.name,
          fileName: product.fileName,
        })
        if(this.order.cost) {
          this.order.cost += product.price * number;
        }else {
          this.order.cost = product.price * number;
        }
      }
      
      //修改后订单存到redis中去
      this.$axios({
        url: '/api/order/modify',
        method: "POST",
        data: this.order
      }).then(rs => {
        console.log("redis中购物车订单修改结果", rs.data.msg);
      })
    },
    getUserId() {
      this.$http
        .post(
          "/api/address/getUserId",
          "token=" + sessionStorage.getItem("token")
        )
        .then((res) => {
          this.userId = res.data.userId;
        });
    },
    addToFavorite(productId) {
      if(!this.roleType) {
        this.$message.warning("请先登录！");
        this.$router.push({name: 'Login'});    
        return;
      }
      this.$axios({
        url: "/api/collection/add",
        method: "POST",
        data: {
          userId: this.userId,
          productId: productId
        }
      }).then(res => {
        if (res.data.code === 5200) {
          this.$message.success("收藏成功");
        } else {
          this.$message.error(res.data.msg || "收藏失败");
        }
      }).catch(err => {
        this.$message.error("网络异常，请稍后再试");
        console.error(err);
      });
    },
    orderByPriceAsc() {
      // this.pageInfo.list
      this.pageInfo.list = this.pageInfo.list.sort((a, b) => a.price - b.price);
    },
    orderByPriceDesc() {
      this.pageInfo.list = this.pageInfo.list.sort((a, b) => b.price - a.price);
    }
  },
  watch: {
    $props: {
      immediate: true,
      deep: true,
      handler(newsProps) {
        this.loadListData(newsProps);
      },
    },
    "order": {
      deep: true,
      handler(newOrder) {
        console.log("检测到order-change:", newOrder);
        this.$store.commit("setOrder", newOrder)
      }
    }
  },
  components: {
    SearchNav,
  },
  props: ["searchTxt", "type", "categoryId"],
  created() {
    this.order = this.$store.state.order
    if(this.roleType) this.getUserId();
  }
};
</script>

<style scope>
  .li-product{
    background-color: aliceblue;
    border: solid rgba(0, 0, 0, 0.336) 1px;
    border-radius: 5px;
  }
  .li-product:hover {
    background-color: aliceblue;
    border: solid red 1px;
  }
</style>